<template>
  <div>
    <!-- 主页面 -->
    <div>
      <crumbs :BreadCrumb="BreadCrumb"></crumbs>
      <!-- 搜索 -->
      <div class="top_b">
        <el-form
            :inline="true"
            :model="searchForm"
            label-position="right"
            style="width: 100%"
        >
            <el-form-item label="客户姓名" :label-width="labelwidth">
              <el-input
                  class="input_c"
                  v-model="searchForm.customerName"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="证件号码" :label-width="labelwidth">
              <el-input
                  class="input_c"
                  v-model="searchForm.credNum"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item
                label="单位名称"
                :label-width="labelwidth"
                prop="chineseName"
            >
              <el-input
                  class="input_c"
                  v-model="searchForm.company"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item
                label="二级部门"
                :label-width="labelwidth"
            >
              <el-input
                  class="input_c"
                  v-model="searchForm.deptname"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item
                label="职务"
                prop="chineseName"
                :label-width="labelwidth"
            >
              <el-select v-model="searchForm.job" clearable>
                <el-option v-for="(v,i) in dict['zwType']" :key="i" :value="v.itemCode"
                           :label="v.itemName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="诊疗ID" :label-width="labelwidth">
              <el-input class="input_c" v-model="searchForm.duty" clearable></el-input>
            </el-form-item>
            <el-form-item
                label="注册时间"
                prop="chineseName"
                :label-width="labelwidth"
            >
              <el-date-picker
                  v-model="searchForm.gmtCreateRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
                label="个人状态"
                prop="chineseName"
                :label-width="labelwidth"
            >
              <el-select v-model="searchForm.status" placeholder="请选择">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课题人员" :label-width="labelwidth">
              <el-checkbox v-model="searchForm.keti"></el-checkbox>
            </el-form-item>
            <el-form-item label="" :label-width="labelwidth" class="search">
              <el-button type="primary" @click="getPeCustomersList">搜索</el-button>
              <el-button type="success" @click="checkSign()">添加</el-button>
            </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <div>
        <el-table
            ref="multipleTable"
            :data="customersList"
            tooltip-effect="dark"
            style="width: 100%; margin-top: 5px"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="customerName" label="姓名" width="100">
          </el-table-column>
          <el-table-column prop="sex" label="性别" width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.sex|formatSex }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80">
          </el-table-column>
          <el-table-column prop="telephone" label="联系方式" width="150">
          </el-table-column>
          <el-table-column prop="company" label="所在单位" width="150">
          </el-table-column>
          <el-table-column prop="nativePlace" label="籍贯" width="150">
            <template slot-scope="scope">
              <span>{{ formatNativePlace(scope.row.nativePlace) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="folk" label="民族" width="80">
            <template slot-scope="scope">
              <span>{{ formatFolk(scope.row.folk)  }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="credNum" label="身份证号" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.credNum|formatCredNum }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="现居地址" width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="status" label="个人状态" width="150">
            <template slot-scope="scope">
              {{ scope.row.status|formatCustomerStatus }}
            </template>
          </el-table-column>
          <el-table-column label="注册时间" width="150">
            <template slot-scope="scope">
              {{ scope.row.gmtCreate|formatDate }}
            </template>
          </el-table-column>
          <el-table-column
              width="250"
              prop="address"
              label="操作"
              fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                  @click="handleClick(scope.row)"
                  style="background: #4dd2d2; color: #ffffff"
                  size="small"
              >编辑
              </el-button>
              <el-button
                  @click="remove(scope.row)"
                  type="danger"
                  size="small"
              >删除
              </el-button>
              <el-button
                  @click="toGetLogs(scope.row)"
                  style="background: #b578ee; color: #ffffff"
                  size="small"
              >体检史
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="searchForm.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="searchForm.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="customersTotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 个人注册 -->
    <el-dialog
        :title="id == null ? '添加' : '编辑'"
        :visible.sync="dialogFormVisible"
        width="1300px"
        class="top_dialog"
        destroy-on-close
    >
      <el-form :model="form" label-position="left">
        <div class="add_info">
          <userinfos ref="riskForm" :dictdata="dict" :queryform="queryform"></userinfos>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
            type="primary"
            style="margin-right: 150px"
            @click="addinsertCustom()"
        >保存
        </el-button
        >
        <el-button @click="clear">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 体检史弹框 -->
    <el-dialog title="体检历史记录" width="1300px" :visible.sync="physicais">
      <div class="tab_box">
        <div class="box_t">
          <el-form
              :inline="true"
              :model="logsForm"
              ref="ruleFormed"
              :rules="rulesed"
          >
            <el-form-item
                label="最近体检时间"
                label-width="150px"
                prop="chineseName"
            >
              <el-date-picker
                  v-model="logsForm.times"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
              >
              </el-date-picker>
              <el-form-item>
                <el-button @click="toGetLogs" type="success">查找</el-button>
              </el-form-item>
            </el-form-item>
          </el-form>
        </div>

        <div class="box_th">
          <div class="t_head">体检记录</div>
          <!-- 列表 -->
          <div>
            <el-table
                border
                :data="logs"
                tooltip-effect="dark"
                style="width: 100%; margin-top: 5px"
            >
              <el-table-column prop="odd" label="体检单号" width="160">
              </el-table-column>
              <el-table-column prop="setmeal" label="体检套餐">
              </el-table-column>
              <el-table-column prop="state" label="体检状态" width="160">
              </el-table-column>
              <el-table-column label="体检时间" width="160">
                <template slot-scope="scope">
                  {{ formatTimes(scope.row.time) }}
                </template>
              </el-table-column>
              <el-table-column
                  label="打印报告时间"
                  width="160"
              >
                <template slot-scope="scope">
                  {{ formatTimes(scope.row.registration) }}
                </template>
              </el-table-column>
              <el-table-column prop="diagnosis" label="诊断结论" width="160">
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div style="text-align: right">
          <el-button @click="physicais = false">关 闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import crumbs from "../../views/Crumbs.vue";
import userinfos from "../common/userinfos.vue";
import {formatTimeToStr} from "@src/common/utils/date";
import {customerStatus} from "@src/common/utils/constant";
import axios from 'axios'

export default {
  components: {
    crumbs,
    userinfos,
  },
  data() {
    return {
      dict: {},
      customerSelected: {},
      customersList: [],
      customersTotal: 0,
      searchForm: {
        gmtCreateRange: [
          formatTimeToStr(new Date(new Date().setFullYear(new Date().getFullYear() - 1))),
          formatTimeToStr(new Date(), "yyyy-MM-dd hh:mm:ss")
        ]
      },
      pageNo: 1,
      pageSize: 10,
      logsForm: {},
      logs: [],
      logsTotal: 0,
      phoneList: [],
      formed: {},
      physicais: false,
      //
      compileis: false,
      labelwidth: "80px",
      formLabelWidth: "80",
      form: {},
      rules: {},
      rucs: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
        ],
        nativePlace: [
          {required: true, message: '请选择籍贯', trigger: 'blur'},
        ],
        marriage: [
          {required: true, message: '请选择婚姻状况', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        birth: [
          {required: true, message: '请输入出生日期', trigger: 'blur'},
        ],
        folk: [
          {required: true, message: '请选择民族', trigger: 'blur'},
        ],
        telephone: {
          type: 'string',
          required: true,
          message: '请输入正确的手机号',
          trigger: 'change',
          pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/
        },
        credNum: {
          type: 'string',
          required: true,
          message: '请输入正确的身份证号码',
          trigger: 'change',
          pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        },

      },
      dialogFormVisible: false,
      BreadCrumb: [
        {path: "", customerName: "检前管理"},
        {path: "", customerName: "个人档案"},
      ],

      value: "123",
      clearable: false,
      roleName: "",
      checkedCities: [],
      checkedCitiess: [],
      cities: [],
      citiess: [],
      id: null,
      options: customerStatus,
      options2: [
        {value: "1", label: "线上预约"},
        {value: "2", label: "线下登记"},
        {value: "3", label: "系统转入"},
      ],
      title: "",
      // select全选
      multipleSelection: [],
      // 个人登记
      checkform: {},
      // 页码
      total: 0,
      queryform: {},
      rulesed: {},
      timehttp: ''
    };
  },
  filters: {
    formatDate: function (time) {
      if (time != null && time !== "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
      } else {
        return "";
      }
    },
    formatCustomerStatus: function (val) {
      const dict = {}
      customerStatus.forEach(v => {
        dict[v.value] = v.label
      })
      if (dict[val] !== undefined) {
        return dict[val]
      }
      return "未知"
    },
    formatSex: function (val) {
      var dict = {1: "男", 2: "女"}
      return dict[val]
    },
    formatCredNum: function (val) {
      if (val !== null) {
        return val.replace(/^(.{6})(?:\d+)(.{4})$/, "\$1****\$2")
      }
      return val

    },
  },
  created() {
    this.searchDictList()
    this.getPeCustomersList();
  },
  beforeDestroy() {
    clearInterval(this.timehttp)
  },
  methods: {
    // 身份证认证
    clear() {
      this.dialogFormVisible = false
      clearInterval(this.timehttp)
    },
    identityCard() {
      this.timehttp = setInterval(() => {
        this.doIdentityCard()
      },2500)
    },
    doIdentityCard(){
      const that = this
      $.ajax({
				type: 'GET',
				timeout: 10000,
				url: 'http://localhost:30088/ID=sfz',
				dataType: 'jsonp',
				success: function(data) {
          let stringtext = data.info
            let listarr = stringtext.split("-")
            listarr[0] = listarr[0].trim()
            listarr[5] = listarr[5].trim()
            listarr[6] = listarr[6].trim()
            // 名字
            that.$set(that.queryform, "customerName", listarr[0])
            // 身份证号
            that.$set(that.queryform, "credNum", listarr[4])
            that.searchForm.credNum = listarr[4]
            // this.$set(this.searchForm, "credNum", listarr[4])
            // 性别
            that.$set(that.queryform, "sex", listarr[1] == "男" ? 1 : 2)
            // 出生日期
            let birthday = listarr[4].slice(6, 14)
            birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
            that.$set(that.queryform, "birth", birthday)
            // 年龄
            var birthDate = new Date(birthday);
            var nowDateTime = new Date();
            var age = nowDateTime.getFullYear() - birthDate.getFullYear();
            that.$set(this.queryform, "age", age)
            // 照片

            function convertBase64UrlToImgFile(urlData, fileName, fileType) {
              var bytes = window.atob(urlData); //转换为byte
              //处理异常,将ascii码小于0的转换为大于0
              var ab = new ArrayBuffer(bytes.length);
              var ia = new Int8Array(ab);
              var i;
              for (i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
              }
              //转换成文件，添加文件的type，name，lastModifiedDate属性
              var blob = new Blob([ab], {type: fileType});
              blob.lastModifiedDate = new Date();
              blob.name = fileName;
              return blob;
            }

            var imgfile = convertBase64UrlToImgFile(data.base64, listarr[4] + '.jpg', 'image/jpg');
            // var _this = this

            function uploadImg(fileData) {
              let formData = new FormData();
              let fileOfBlob = new File([fileData], listarr[4] + ".jpg"); // 命名图⽚名
              formData.append("file", fileOfBlob);
              axios.post(
                  "/pbFile/importFile",
                  formData,
                  {
                    header: {"Content-Type": "application/x-www-form-urlencoded"},
                  }
              ).then(res => {
                that.$set(that.queryform, "photo", res.data.data)
              })
            }

            uploadImg(imgfile)
				},
				error: function(err) {
          console.log('err', err)
				}
			})
    },
    searchDictList() {
      this.$axios.searchDictList({
        codes: ["tyType", "xmType", "jgType", "mzType", "gwType", "zwType", "ybType", "dwxzType", 'zylbType', 'zjType'],
      }).then((res) => {
        if (res.code === "00000") {
          res.data.forEach(v => {
            this.dict[v.dictCode] = v.items
          })
        }
      });
    },
    formatFolk (val) {
      const map = {}
      this.dict.mzType && this.dict.mzType.forEach(v=>{
        map[v.dictItemId] = v.itemName
      })
      if(map[val] !== undefined){
        return map[val]
      }
      return val
    },
    formatNativePlace (val) {
      const map = {}
      this.dict.jgType && this.dict.jgType.forEach(v=>{
        map[v.dictItemId] = v.itemName
      })
      if(map[val] !== undefined){
        return map[val]
      }
      return val
    },
    forceupdata() {
      this.$forceUpdate();
    },
    // 登记审核
    checkSign() {
      this.dialogFormVisible = true;
      this.id = null;
      this.title = "添加信息";
      this.queryform = {}
      // 身份证认证
      this.identityCard()
    },
    // 个人登记
    addinsertCustom(formName) {
      // 在这里验证
      this.$refs.riskForm.$refs.riskFormRef.validate((valid) => {
        if (valid) {
          // 获取子组件form
          this.checkform = this.$refs.riskForm.$refs.riskFormRef.model;
          if (this.id == null) {
            this.$axios.insertPeCustomers({...this.checkform,}).then((res) => {
              if (res.code == "00000") {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.dialogFormVisible = false;
                this.getPeCustomersList();
              }
            });
          } else {
            this.$axios.updatePeCustomers({...this.checkform}).then((res) => {
              if (res.code == "00000") {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.dialogFormVisible = false;
                this.getPeCustomersList();
              }
            });
          }
          // console.log("子组件表单信息：",this.checkform)
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    // 编辑
    handleClick(row) {
      this.$axios.getPeCustomersById({
        peCustomersId: row.id,
      }).then((res) => {
        if (res.code === "00000") {
          this.id = row.id;
          this.queryform = res.data ;
          this.title = "编辑信息";
          this.dialogFormVisible = true;
        }
      });
    },
    remove(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.deletePeCustomers({
          peCustomersId: row.id
        }).then(res => {
          if (res.code === '00000') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getPeCustomersList();
            this.getLogs(this.medicalhistory)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 查询客户信息
    toGetPerson(row) {
      this.$axios
          .getPeCustomerById({
            peCustomersId: row.id,
          })
          .then((res) => {
            if (res.code == "00000") {
              this.id = res.data.id;
              let resData = res.data;
              console.log(resData);
              this.form = {...resData};
            }
          });
      this.compileis = !this.compileis;
    },
    // 体检史
    toGetLogs(row) {
      this.customerSelected = row
      console.log(row)
      var req = {peCustomersId: row.id}
      if (this.logsForm.times && this.logsForm.times.length === 2) {
        req['startTime'] = this.logsForm.times[0]
        req['endTime'] = this.logsForm.times[1]
      }
      this.$axios
          .getPeCustomerLogs(req)
          .then((res) => {
            if (res.code == "00000") {
              this.logs = res.data.records;
              this.logsTotal = res.data.total;
            }
          });
      this.physicais = true;
    },
    // 保存按钮
    editPerson(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = {
            ...this.form,
          };
          if (this.id == null) {
            this.$axios
                .insertPeCustomers({
                  ...formData,
                })
                .then((res) => {
                  if (res.code == "00000") {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    this.compileis = false;
                    this.getPeCustomersList();
                  }
                });
          } else {
            this.$axios
                .updatePeCustomer({
                  id: this.id,
                  ...formData,
                })
                .then((res) => {
                  if (res.code === "00000") {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    this.getPeCustomersList();
                    this.compileis = false;
                  }
                });
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 权限选择事件
    handleCheckedCitiesChange(row) {
      console.log(row);
    },

    // 列表删除
    deleteRole(row) {
      this.$confirm("此操作将删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
    },
    // 表单输入
    // bindinput() {
    //   console.log("qw3");
    //   this.getPeCustomersList();
    // },
    // 所有信息查询
    getPeCustomersList() {
      if (this.searchForm.gmtCreateRange && this.searchForm.gmtCreateRange.length === 2) {
        this.searchForm.startDate = this.searchForm.gmtCreateRange[0]
        this.searchForm.endDate = this.searchForm.gmtCreateRange[1]
      }
      this.doGetList({...this.searchForm})

    },
    doGetList(req) {
      this.$axios.getPeCustomersList(req).then((res) => {
        if (res.code == "00000") {
          this.customersList = res.data.records;
          this.customersTotal = res.data.total;
        }
      });
    },
    // 每页几条
    handleSizeChange(val) {
      this.pageSize = val;
      this.doGetList({...this.searchForm, pageSize: this.pageSize, pageNo: this.pageNo})
    },
    // 第几页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.doGetList({...this.searchForm, pageSize: this.pageSize, pageNo: this.pageNo})
    },
  },
};
</script>

<style scoped>
.top_but {
  margin-left: 20px;
}

.top_buts {
  margin-top: 10px;
  margin-bottom: 10px;
}

.pagination {
  text-align: center;
}

.top_b {
  display: flex;
}

.dialog {
  /* width:900px; */
  /* margin:0px auto; */
}

/*  */

/* .el-select {
  width: 300px;
} */

.el-select /deep/ .el-input__inner {
  width: 100%;
}

::v-deep .input_c .el-input__inner {
  width: 100%;
}

::v-deep .el-dialog__body {
  border-bottom: 1px solid #cccccc;
  margin: 0 20px;
  padding: 20px 20px 0px;
  /* padding: 20px; */
}

.date {
  text-align: right;
  color: #7f7f7f;
  font-weight: bold;
}

.info_l {
  /* width: 80%; */
  margin: 0px auto;
}

.info_l_input {
  width: 82%;
}

.info_sel_r_groupn {
  margin-left: 40px;
}

.form-row {
  overflow: hidden;
}

.form-col {
  float: left;
}

.info_sel_r_img {
  width: 180px;
  height: 220px;
  margin: 0px auto;
}

.avatar-uploader {
  margin: 0px auto;
  text-align: center;
}

.info_l /deep/ .el-select {
  width: 100%;
}

.info_l_head {
}

.el-table th > .cell {
  white-space: nowrap;
}

.tan_k {
  display: flex;
  justify-content: space-between;
}

.textarea {
  width: 350px;
  height: 120px;
}

.el-textarea /deep/ .el-textarea__inner {
  min-height: 89px;
  height: 89px;
}

.text_a {
  width: 50%;
  margin-left: 20px;
}

.text_a > span {
  width: 100%;
  display: inline-block;
  border-bottom: 1px solid #cccccc;
}

.add_jian {
  padding-top: 15px;
}

.add_jian > span {
  display: block;
  color: #3298d3;
  font-size: 8px;
  line-height: 24px;
}

::v-deep .el-dialog__body {
  border: 0px;
}

.dialog /deep/ .el-dialog {
  margin-top: 3vh !important;
}

.search {
  margin-left: 30px;
}
</style>
